package gone

import (
	"context"
	"fmt"
	"gonexample/gone/config"
	"gonexample/routers"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"

	"github.com/gin-gonic/gin"
)

// Start 框架启动
func Start() {
	gin.SetMode(config.Server.RunMode)
	routersInit := routers.Routers()
	readTimeout := config.Server.ReadTimeout
	writeTimeout := config.Server.WriteTimeout
	endPoint := fmt.Sprintf(":%d", config.Server.HttpPort)
	maxHeaderBytes := 1 << 20

	srv := &http.Server{
		Addr:           endPoint,
		Handler:        routersInit,
		ReadTimeout:    readTimeout,
		WriteTimeout:   writeTimeout,
		MaxHeaderBytes: maxHeaderBytes,
	}

	log.Printf("HTTP 服务启动，端口 %s", endPoint)

	go func() {
		// 服务连接
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()

	// 等待中断信号以优雅地关闭服务器（设置 5 秒的超时时间）
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit
	log.Println("正在停止服务 ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("服务已停止:", err)
	}
	log.Println("服务已停止")
}
